package com.xzz.directprint.util;

/**
 * @Author: zhanglm
 * @CreateDate: 2024-11-21 12:36
 * @FullNameClass: com.xzz.directprint.test.PdfPrinter
 * @Description:
 */

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;

public class PdfPrinter {


    public static boolean printPdf(String pdfFilePath) throws IOException, PrinterException {
        // Load the PDF file
        boolean flag = false;
        try (PDDocument document = PDDocument.load(new File(pdfFilePath))) {
            // Get the default PrintService
            PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();

            if (defaultPrintService != null) {
                // Create a PrinterJob
                PrinterJob printerJob = PrinterJob.getPrinterJob();
                printerJob.setPrintService(defaultPrintService);

                // Wrap the PDF document in a Printable object
                PDFPageable pdfPageable = new PDFPageable(document);

                // Do the printing
                printerJob.setPageable(pdfPageable);
                try {
                    printerJob.print();
                } catch (PrinterException e) {
                    flag = true;
                    e.printStackTrace();
                }
            } else {
                flag = true;
                System.out.println("No default printer found.");
            }
        }
        return flag;
    }

//    public static void main(String[] args) {
//        try {
//            printPdf("d:/tuzhi/输出轴12345A12.pdf");
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (PrinterException e) {
//            throw new RuntimeException(e);
//        }
//    }
}
